package fr.lille.inria.adam.lifl.EcoGardeInventory.Services;

import static fr.lille.inria.adam.lifl.EcoGardeInventory.Utils.CommonUtilities.EXTRA_SHAKE;
import static fr.lille.inria.adam.lifl.EcoGardeInventory.Utils.CommonUtilities.HANDLE_SHAKE_ACTION;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import fr.lille.inria.adam.lifl.EcoGardeInventory.ShakeEventListener;
import fr.lille.inria.adam.lifl.EcoGardeInventory.ShakeEventListener.OnShakeListener;

public class ShakeListnerService extends Service{

	private final String TAG = ShakeListnerService.class.getSimpleName();
	private SensorManager mSensorManager;
	private ShakeEventListener mSensorListener;

	@Override
	public void onCreate() {
		super.onCreate();
		
		Log.d(TAG, "onCreat'd");
	}

	@Override
	public void onStart(Intent mIntent, int mStartId) {
		super.onStart(mIntent, mStartId);
		
		startservice();
		
		Log.d(TAG, "onStart'd");
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		
		mSensorManager.unregisterListener(mSensorListener);
		
		Log.d(TAG, "onDestroy'd");
	}

	@Override
	public IBinder onBind(Intent mIntent) {
		return null;
	}

	private void startservice() {
		mSensorListener = new ShakeEventListener();
		
		mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		
		mSensorManager.registerListener(mSensorListener,
				mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SensorManager.SENSOR_DELAY_FASTEST);

		mSensorListener.setOnShakeListener(new OnShakeListener() {

			public void onShake() {
				Toast.makeText(ShakeListnerService.this, "shake !!!",
						Toast.LENGTH_SHORT).show();
				
				Intent intent = new Intent(HANDLE_SHAKE_ACTION);
		        
				intent.putExtra(EXTRA_SHAKE, "basicShakeEvent");
		        
				sendBroadcast(intent);
			}
		});

		Log.d(TAG, "ShakeListnerService is start'd!");
	}
}
